package com.tianxin.workbao.workBao.dataProvide;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.tianxin.workbao.workBao.R;
import com.tianxin.workbao.workBao.bean.MobileChart;
import com.tianxin.workbao.workBao.bean.MobileChartDao;
import com.tianxin.workbao.workBao.common.Constant;
import com.tianxin.workbao.workBao.common.URL;
import com.tianxin.workbao.workBao.helper.GreenDaoHelper;
import com.tianxin.workbao.workBao.listener.UpdateListViewListener;
import com.tianxin.workbao.workBao.okhttp.CommonOkHttpClient;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataHandle;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataListener;
import com.tianxin.workbao.workBao.okhttp.request.CommonRequest;
import com.tianxin.workbao.workBao.okhttp.request.RequestParams;
import com.tianxin.workbao.workBao.utils.common.BeansUtil;
import com.tianxin.workbao.workBao.utils.common.DateUtilLast;
import com.tianxin.workbao.workBao.utils.common.NetworkUtils;
import com.tianxin.workbao.workBao.utils.common.UIUtils;

import org.greenrobot.greendao.query.Query;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hacker on 2017/7/18.
 */

public class InOutDataProvide extends BaseDataProvide {
    private List<MobileChart> mDatas;
    private Integer inOrOutType;
    private int isFromServer;
    private int staticType;
    private UpdateListViewListener mUpdateListViewListener;
    private Handler mSaveDbHandler;
    private int mPage = 1;

    public InOutDataProvide(Context context, UpdateListViewListener listener, int type, int staticType) {
        super(context);
        this.mUpdateListViewListener = listener;
        isFromServer = 0;
        this.inOrOutType = type;
        this.staticType = staticType;
        mSaveDbHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                MobileChartDao chartDao = GreenDaoHelper.newInstance().getDaoSession().getMobileChartDao();
                JSONObject jsonObject = null;
                try {
                    String dataString = msg.obj.toString();
                    if (dataString.startsWith("[") && dataString.endsWith("]") && dataString.length() > 3) {
                        List<MobileChart> charts = BeansUtil.mobileChartToBeans(dataString);
                        mDatas = charts;
                        refreshUI();
                        for (int i = 0; i < charts.size(); i++) {
                            chartDao.insertOrReplace(charts.get(i));
                        }
                    } else {
                        MobileChart chart = BeansUtil.mobileChartToBean(dataString);
                        chartDao.insertOrReplace(chart);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
    }


    private void getFromDb(Integer type, int page) {
        MobileChartDao chartDao = GreenDaoHelper.newInstance().getDaoSession().getMobileChartDao();
        String timeTag = "";
        Date date = new Date();
        switch (staticType) {
            case TODAY_DATA:
                timeTag = dateFormat.format(date);
                break;
            case WEEK_DATA:
                timeTag = dateYearFormat.format(date) + "--" + DateUtilLast.getCurrWeekOfYear(date);
                break;
            case MONTH_DATA:
                timeTag = dateMonthFormat.format(date);
                break;
            case SEASON_DATA:
                timeTag = dateYearFormat.format(date) + "-" + DateUtilLast.getQuarterOfYear(date);
                break;
            case YEAR_DATA:
                timeTag = dateYearFormat.format(date);
                break;
        }
        Query<MobileChart> query = chartDao.queryBuilder()
                .where(MobileChartDao.Properties.TimeTag.eq(timeTag))
                .where(MobileChartDao.Properties.Type.eq(type))
                .limit(1)
                .build();
        mDatas = query.list();
        refreshUI();
    }

    /**
     * get from server
     */
    public void getFromServer() {
        if (!NetworkUtils.isConnected(UIUtils.getContext())) {
            mUpdateListViewListener.hideProgress();
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
        } else {
            mUpdateListViewListener.showProgress();
            isFromServer = 1;
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            map.put("statictype", staticType + "");
            map.put("type", inOrOutType + "");
            RequestParams params = new RequestParams(map);
            String url = URL.getStaticUrl();
            CommonOkHttpClient.post(CommonRequest.createPostRequest(url, params), getDisposeDataHandle());
        }
    }

    /**
     * 真正处理返回数据
     *
     * @param responseObj
     */
    private void handleResponseObj(Object responseObj) {
        try {
            JSONObject jsonObject = new JSONObject(responseObj.toString());
            int status = jsonObject.getInt(Constant.RESPONSE_STATUS);
            if (status > 0) {
                String resString = jsonObject.getString(Constant.RESPONSE_DATA);
                if (resString.startsWith("[") && resString.endsWith("]")) {
                    if (jsonObject.getJSONArray(Constant.RESPONSE_DATA) != null) {
                        // 保存到数据库中
                        Message message = Message.obtain();
                        message.arg1 = 1;
                        message.obj = resString;
                        mSaveDbHandler.sendMessage(message);
                    } else {
                        mUpdateListViewListener.showMessage(jsonObject.getString(Constant.RESPONSE_INFO));
                    }
                } else {
                    if (jsonObject.getJSONObject(Constant.RESPONSE_DATA) != null) {
                        // 保存到数据库中
                        Message message = Message.obtain();
                        message.arg1 = 1;
                        message.obj = resString;
                        mSaveDbHandler.sendMessage(message);
                    } else {
                        mUpdateListViewListener.showMessage(jsonObject.getString(Constant.RESPONSE_INFO));
                    }
                }

            } else {
                mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.no_data));
            }
        } catch (JSONException e) {
            showRequestErrorMessage(mUpdateListViewListener,responseObj.toString());
            e.printStackTrace();
        }
    }

    @Override
    public DisposeDataHandle getDisposeDataHandle() {

        if (disposeDataHandle == null) {
            disposeDataHandle = new DisposeDataHandle(getDisposeDataListener());
        }
        return disposeDataHandle;
    }

    @Override
    public DisposeDataListener getDisposeDataListener() {
        if (disposeDataListener == null) {
            disposeDataListener = new DisposeDataListener() {
                @Override
                public void onSuccess(Object responseObj) {
                    mUpdateListViewListener.hideProgress();
                    if (responseObj.equals(null)) {
                        mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.no_response));
                    } else {
                        handleResponseObj(responseObj);
                    }
                }

                @Override
                public void onFailure(Object reasonObj) {
                    mUpdateListViewListener.hideProgress();
                    showRequestErrorMessage(mUpdateListViewListener,reasonObj.toString());
                }
            };
        }
        return disposeDataListener;
    }

    public void getdatas(Integer type, int page) {
        getFromServer();
        if (mDatas != null && !mDatas.isEmpty()) {
            mUpdateListViewListener.onRefreshData(mDatas);
        } else {
            getFromDb(type, page);
        }
    }

    @Override
    public void refreshUI() {
        if (mDatas != null && !mDatas.isEmpty()) {
            if (mPage > 1) {
                mUpdateListViewListener.onLoadMoreData(mDatas);
            } else {
                mUpdateListViewListener.onRefreshData(mDatas);
            }
        }
    }

    public void search(String query) {

    }
}
